package com.isyscore.os.metadata.route;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import com.isyscore.device.common.model.RespDTO;
import com.isyscore.device.common.util.JsonMapper;
import com.isyscore.os.core.properties.RouteInfoProperties;
import com.isyscore.os.permission.exception.ErrorCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.SmartLifecycle;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
@Slf4j
@EnableConfigurationProperties(RouteInfoProperties.class)
public class RouteRegisterLifecycle implements SmartLifecycle {
    @Autowired
    private RouteInfoProperties routeInfoProperties;

    @Override
    public void start() {
        if (CollUtil.isNotEmpty(routeInfoProperties.getExcludeUrl())) {
            Map<String, String> paramMap = Maps.newHashMap();
            paramMap.put("path", "/api/udmp/metadata/**");
            paramMap.put("serviceId", routeInfoProperties.getServiceId());
            paramMap.put("url", "http://isc-metadata-service:36400");
            paramMap.put("excludeUrl", StrUtil.join(";", routeInfoProperties.getExcludeUrl()));
            try {
                HttpResponse response = HttpRequest.post(routeInfoProperties.getRouterService() + routeInfoProperties.getRefreshRoutePath())
                        .contentType("application/json")
                        .body(JsonMapper.toNonDefaultJson(paramMap))
                        .timeout(5000)
                        .execute();
                RespDTO respDTO = JSONObject.parseObject(response.body(), RespDTO.class);
                if (!response.isOk() || respDTO.getCode() != ErrorCode.OK.getCode()) {
                    log.error("刷新路由信息失败，状态码为：{},返回信息为：{}", response.getStatus(), respDTO.getMessage());
                }
            } catch (Exception e) {
                log.error("刷新路由信息发生异常:{}", e.getMessage());
            }
        }

        try {
            Map<String, List<String>> headers = new HashMap<String, List<String>>() {{
                put("Content-Type", Collections.singletonList("application/json"));
                put("isc-api-version", Collections.singletonList("2.1"));
                put("isc-tenant-id", Collections.singletonList("system"));
            }};
            Map<String, Object> body = new HashMap<String, Object>() {{
                put("code", "udmp");
                put("introduction", "通用数据管理主要面向数据开发及运维人员，提供了数据集成、数据治理、数据开发与运维等服务，为各个物联场景提供数据服务。");
                put("name", "通用数据管理");
                put("type", 0);
                put("secondType", 2);
                put("version", "v7.3.0");
                put("inMenu", 1);
                put("aclReturnUrl", "http://isc-metadata-service:36400/api/udmp/metadata/system/aclReturn");
            }};
            HttpRequest request = HttpRequest.post(routeInfoProperties.getRegisterUrl())
                    .contentType(MediaType.APPLICATION_JSON_VALUE)
                    .timeout(5000)
                    .header(headers)
                    .body(JsonMapper.toAlwaysJson(body));
            HttpResponse response = request.execute();
            RespDTO respDTO = JSONObject.parseObject(response.body(), RespDTO.class);
            if (!response.isOk() || respDTO.getCode() != ErrorCode.OK.getCode()) {
                log.error("往 rc 注册信息失败 url={} message={}", routeInfoProperties.getRegisterUrl(), respDTO.getMessage());
            }
        } catch (Exception e) {
            log.error("往 rc 注册信息失败 url={} message={}", routeInfoProperties.getRegisterUrl(), e.getMessage());
        }

        migrationServer();
    }


    public void migrationServer() {
        Map<String, String> paramMap = Maps.newHashMap();
        paramMap.put("path", "/api/migrate/**");
        paramMap.put("serviceId", "isc-migration-service");
        paramMap.put("url", "http://isc-migration-service:36401");
//            paramMap.put("excludeUrl", StrUtil.join(";", routeInfoProperties.getExcludeUrl()));
        try {
            HttpResponse response = HttpRequest.post(routeInfoProperties.getRouterService() + routeInfoProperties.getRefreshRoutePath())
                    .contentType("application/json")
                    .body(JsonMapper.toNonDefaultJson(paramMap))
                    .timeout(5000)
                    .execute();
            RespDTO respDTO = JSONObject.parseObject(response.body(), RespDTO.class);
            if (!response.isOk() || respDTO.getCode() != ErrorCode.OK.getCode()) {
                log.error("migrate刷新路由信息失败，状态码为：{},返回信息为：{}", response.getStatus(), respDTO.getMessage());
            }
        } catch (Exception e) {
            log.error("migrate刷新路由信息发生异常:{}", e.getMessage());
        }
    }

    @Override
    public void stop() {

    }

    @Override
    public boolean isRunning() {
        return false;
    }
}
